package com.sunshine.controller.admin;

import com.sunshine.authorization.annotation.Authorization;
import com.sunshine.authorization.annotation.CurrentUser;
import com.sunshine.authorization.domain.User;
import com.sunshine.authorization.manager.TokenManager;
import com.sunshine.authorization.model.TokenModel;
import com.sunshine.authorization.repository.UserRepository;
import com.sunshine.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static com.sunshine.util.Result.json;

/**
 * 获取和删除token的请求地址，在Restful设计中其实就对应着登录和退出登录的资源映射
 *
 * @author ScienJus
 * @date 2015/7/30.
 */
@RestController
@RequestMapping("/admin/auth")
public class AdminAuthController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TokenManager tokenManager;

    @RequestMapping(method = RequestMethod.POST)
    public Map<String, Object> login(@RequestParam(value = "user_name") String username,
                                     @RequestParam(value = "pwd") String password) {
        User user = userRepository.findByUsername(username);
        if (user == null ||  //未注册
                !user.getPassword().equals(password)) {  //密码错误
            //提示用户名或密码错误
            return json(Result.STATUS_CODE.SYSTEM_ERRO);
        }
        //生成一个token，保存用户登录状态
        TokenModel model = tokenManager.createToken(user.getId());
        model.setNickName(user.getNickname());
        model.setToken(String.valueOf(model.getUserId()) + '_' + model.getToken());
        return json(Result.STATUS_CODE.SUCCESS, model);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    @Authorization
    public Map<String, Object> logout(@CurrentUser User user) {
        tokenManager.deleteToken(user.getId());
        return json(Result.STATUS_CODE.SUCCESS);
    }

}
